package ua.com.softway.mail;

public class Mailer {
	private static SendMailThread sendMailThread;
	private static MailQueue mailQueue;
	
	public static void init(MailerConfig mailConfig) {
        if (mailQueue != null) throw new IllegalStateException("Init is already called");
        
	    mailQueue = new MailQueue(mailConfig.sendBatchSize, mailConfig.getMessageStatesToSend());
	    
	    sendMailThread = new SendMailThread(mailQueue, mailConfig);
	    sendMailThread.start();
	}
	
	public static void tearDown() {
	    if (mailQueue == null) throw new IllegalStateException("Init not called");
	    
	    mailQueue = null;
	    
	    sendMailThread.interrupt();
	    sendMailThread = null;
	}
	
	static MailQueue getQueue() {
        if (mailQueue == null) throw new IllegalStateException("Call init");
        
	    return mailQueue;
	}
	
	public static void notifyMailer() {
	    synchronized (getQueue()) {
            getQueue().notifyAll();
        }
	}

}
